package com.fengycx.template;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.fengycx.constants.Constants;
import com.fengycx.constants.GlobalExceptionCode;
import com.fengycx.pojo.dto.WxCode2OpenIdDto;
import com.fengycx.properties.DriverAppRegisterProp;
import com.fengycx.utils.AssertUtil;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WechatTemplate {


    private DriverAppRegisterProp driverAppRegisterProp;

    //有参构造器注入，是从WechatAutoConfiguration.class里面拿的，然后复制给上面的全局变量 private DriverAppRegisterProp driverAppRegisterProp;
    public WechatTemplate(DriverAppRegisterProp driverAppRegisterProp){
        this.driverAppRegisterProp=driverAppRegisterProp;
    }

    public String getOpenId(String openIdCode){
        //前端通过微信官方接口 获得的code，然后通过code获取openid 和sessionkey
        String urlPath = String.format(Constants.APP_CODE2_OPENID_URL, driverAppRegisterProp.getAppId(), driverAppRegisterProp.getSecretKey(), openIdCode);
        String response = HttpUtil.get(urlPath);
        //获得的sessionkey和openid转化为对象
        WxCode2OpenIdDto code2OpenId = JSONUtil.toBean(response, WxCode2OpenIdDto.class);
        String openid = code2OpenId.getOpenid();
        AssertUtil.isNotNull(openid, GlobalExceptionCode.PARAM_CODE_ERROR);
        return openid;
    }

}
